#include <vector>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <sys/vfs.h>
#include <sys/stat.h>
//#include "../adaptors.h"
#include "playlist.h"
#include "../bass.h"
using namespace std;
bool file_exists(const char* fname)
{
    struct stat buf;
    return (stat(fname, &buf) ==0);
}

playlist::playlist()
{
    this->clear();
}
playlist::playlist(char* fname)
{
    this->clear();
    load(fname);
}
void playlist::clear()
{
    cur_id = 0;
    lst.clear();
}
void playlist::add( char *fname)
{
    if (!file_exists(fname)) return;
    Trec trc;
    trc.f_path = fname;
    HSTREAM hndl = BASS_StreamCreateFile(false, fname, 0, 0, 0 or BASS_UNICODE);
    QWORD curlen = BASS_ChannelGetLength(hndl, BASS_POS_BYTE);
    trc.duration = BASS_ChannelBytes2Seconds(hndl, curlen);
    BASS_StreamFree(hndl);
    lst.push_back(trc);
    //trc.decoder_type = _detect();
}

unsigned int playlist::selected_id()
{
    return this->cur_id;
}
void playlist::set_id(unsigned int id)
{
    this->cur_id = id;
}

void playlist::load(char *fname)
{
    if (!file_exists(fname)) return;
    this->file_name = fname;
    FILE *fin;
    fin = fopen(fname, "r");
    while (!feof(fin))
    {
        char *str = new char;
        fscanf(fin, "%s", str);
        this->add(str);
        delete str;
    }
    fclose(fin);
}

Trec playlist::get(unsigned int id)
{
    Trec res; res.duration = -1; res.f_path = NULL;
    if (id >= lst.size())
        return res;
    res = lst[id];
    return res;
}

unsigned int playlist::size()
{
    return lst.size();
}
